package com.mdd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.common.R;
import com.mdd.pojo.Category;
import com.mdd.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理
 */

@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping
    @CacheEvict(value = "categoryCache",allEntries = true)
    public R<String> addCategory(@RequestBody Category category){
        categoryService.save(category);
        return R.success("添加成功");
    }

    /**
     * 分类的分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    @Cacheable(value = "categoryCache",key = "#page+'_'+#pageSize")
    public R<Page<Category>> pageSelect(int page,int pageSize){
        //分页对象
        Page<Category> categoryPage = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //按照升序进行查询
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(categoryPage,queryWrapper);
        return R.success(categoryPage);
    }


    /**
     * 删除分类
     * @param id
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "categoryCache",allEntries = true)
    public R<String> deleteCategory(@RequestParam("ids") Long id){
        categoryService.remove(id);
        return R.success("删除成功");
    }

    /**
     * 通过id修改分类信息
     * @param category
     * @return
     */
    @PutMapping()
    @CacheEvict(value = "categoryCache",allEntries = true)
    public R<String> updateCategory(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功!");
    }

    /**
     * 获取该菜品或者套餐的所有分类
     * @param type
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> getList(Integer type){
        //获得条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();

        //根据type查询所有分类
        queryWrapper.eq(type!=null,Category::getType,type).orderByAsc(Category::getSort).orderByAsc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrapper);

        if (list.size()==0)return R.error("暂无菜品分类");
        return R.success(list);
    }
}
